package com.acme.bankapp.service.bank;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.exceptions.ClientExistsException;

public class BankService {
	
	private final String fileName = "bankFeedFile.ser";
	
	/**
	 * Add new clients to Bank object, just calls Bank's method
	 * @param bank
	 * @param client
	 */
	public void addClient(Bank bank, Client client) throws ClientExistsException{
		bank.addClient(client);
		this.saveBank(bank);
		System.out.printf("Serialized data is saved in " + fileName + "\n");
	}
	

	public void printMaximumAmountToWithdraw(Bank bank){
		List<Client> clients = bank.getClients();
		for (Client client: clients){
			System.out.println(client.getMaximumAmountToWithdraw());
		}

	}
	
	public void saveBank(Bank bank){
		try{
			FileOutputStream fileOut = new FileOutputStream(fileName);
			ObjectOutputStream out = new ObjectOutputStream(fileOut);
			out.writeObject(bank);
			out.close();
			fileOut.close();
		}catch(IOException i){
			i.printStackTrace();
		}
	}
	
	public Bank readBank(String filePath){
		Bank bank = new Bank();
		try{
			FileInputStream fileIn = new FileInputStream(filePath);
			ObjectInputStream in = new ObjectInputStream(fileIn);
			bank = (Bank) in.readObject();
			in.close();
			fileIn.close();
		}catch(IOException i){
			i.printStackTrace();
		}catch(ClassNotFoundException c){
			System.out.println("Bank class not found");
			c.printStackTrace();
		}
		return bank;
	}
}
